package com.idatax.auth.controller;

import com.idatax.auth.common.jwt.JwtUtils;
import com.idatax.auth.dto.AuthResult;
import com.idatax.auth.dto.LoginRequest;
import com.idatax.auth.dto.LoginResponse;
import com.idatax.auth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public LoginResponse login(@RequestBody LoginRequest loginRequest) {
        LoginResponse response = new LoginResponse();
        
        AuthResult authResult = userService.authenticate(loginRequest);
        if (authResult.isAuthenticated()) {
            String token = jwtUtils.generateToken(loginRequest.getUsername(), authResult.getClaims());
            response.setToken(token);
            response.setSuccess(true);
            response.setMessage("Login successful");
        } else {
            response.setSuccess(false);
            response.setMessage("Invalid username or password");
        }
        
        return response;
    }
}
